#import "MainWindowController.h"
#import "JSON.h"

@implementation MainWindowController

@synthesize word;

// Make sure objects are released
-(void)dealloc{
    [word release];
    [super dealloc];
}

-(id)init
{
	self = [super init];
	return self;
}

- (IBAction)LookUP:(id)sender {
    
}

- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	
	[self searchTableView];
}

-(void)awakeFromNib{
	[webView loadHTMLString:@"<body style=\"background:#D1EEEE\"><font size=4><b>Please enter a word.</b></font>" baseURL:nil];
}

- (void) searchTableView {
	//webView.backgroundColor = [UIColor blueColor];
	
	NSString *searchText = searchBar.text;
	NSLog(@"searchText: %@", searchText);
	NSMutableArray *searchArray = [[NSMutableArray alloc] init];
	
	//prepar request
	NSString *urlString = [NSString stringWithFormat:@"http://folkets-lexikon.csc.kth.se/folkets/folkets/lookupword"];
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	//set headers
	NSString *contentType = [NSString stringWithFormat:@"text/x-gwt-rpc; charset=utf-8"];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	//create the body
	NSMutableData *postBody = [NSMutableData data];
	
	[postBody appendData:[[NSString stringWithFormat:@"5|0|7|http://folkets-lexikon.csc.kth.se/folkets/folkets/|C42B706916C52B6E655EB5B8852CDE12|se.algoritmica.folkets.client.LookUpService|lookUpWord|se.algoritmica.folkets.client.LookUpRequest|se.algoritmica.folkets.client.LookUpRequest/1089007912|"] dataUsingEncoding:NSUTF8StringEncoding]];
	[postBody appendData:[[NSString stringWithFormat:searchText] dataUsingEncoding:NSUTF8StringEncoding]];
	[postBody appendData:[[NSString stringWithFormat:@"|1|2|3|4|1|5|6|1|0|0|7|"] dataUsingEncoding:NSUTF8StringEncoding]];
	
	//post
	[request setHTTPBody:postBody];
	
	//get response
	NSHTTPURLResponse* urlResponse = nil;  
	NSError *error = [[NSError alloc] init];  
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
	NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	NSLog(@"Response Code: %d", [urlResponse statusCode]);
	if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
		//NSLog(@"Response: %@\n\n", result);
		[self parseResponse:response];
		
		
	}
	
	[searchArray release];
	searchArray = nil;
}


- (void) parseResponse:(NSString *)response
{	
	// Create new SBJSON parser object
	SBJsonParser *parser = [[SBJsonParser alloc] init];
	//NSLog(@"%@",response);
	//response = [response substringFromIndex: 4];
	response = [response substringWithRange: NSMakeRange (5, [response length]-10)];
	 NSRange index = [response rangeOfString:@"["];
	response = [response substringFromIndex: index.location];
	//response = [response substringWithRange: NSMakeRange (4, [response length]-9)];
	NSLog(@"%@",response);
	//response = [response substringWithRange: NSMakeRange (41, [response length]-46)];
	NSMutableString *mutableResponse = @"";
	NSArray *statuses = [parser objectWithString:response error:nil];
	result = @"";
	word = [[Word alloc]init]; 
	[[self word]setContent:@""];
	prevElementName=@"";
	for (NSDictionary *status in statuses)
	{
		//NSLog(@"%@\n\n",status);
		NSString *strTemp = status;
		NSRange match;
		
		match = [strTemp rangeOfString: @">"];
		
		if (match.location == NSNotFound)
		{
			//NSLog (@"Match not found");
			continue;		
		}
		else
		{
			
			mutableResponse = [NSString stringWithFormat: @"%@", status];
	
			NSData *xmlData =[status dataUsingEncoding:NSUTF8StringEncoding];
			//NSLog(@"%@\n\n",xmlData);
			NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
			if (parser == nil) NSLog(@"parser = nil");
			
			[parser setDelegate:self];
			[parser setShouldResolveExternalEntities:YES];
			[parser parse];
		    result =[word ToString];
			result = [result stringByReplacingOccurrencesOfString:@"&;#39;" withString:@"'"];
			result = [result stringByReplacingOccurrencesOfString:@"&#39;" withString:@"'"];
			result = [result stringByReplacingOccurrencesOfString:@"&amp;quot;" withString:@""];
		    result = [result stringByReplacingOccurrencesOfString:@"&amp" withString:@"&"];
		    result = [result stringByReplacingOccurrencesOfString:@"&lt" withString:@"["];
			result = [result stringByReplacingOccurrencesOfString:@"&gt" withString:@"]"];	
			result = [result stringByReplacingOccurrencesOfString:@"&quot;" withString:@""];	
			result = [result stringByReplacingOccurrencesOfString:@"\n" withString:@"<br />"];	
			[webView loadHTMLString:result baseURL: nil];
			
			//webView.text=result;
			break;
		}
		
	}
	if ([result isEqualToString:@""]) 
		//webView.text = @"Word not found!";
		[webView loadHTMLString:@"Word not found!" baseURL: nil];
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if ((elementName==nil)||(nil==[attributeDict objectForKey:@"value"])) return;
	
	//NSLog(@"-----------elementName: %@", elementName);
	//NSLog(@"--- %@", attributeDict);
	if([elementName isEqualToString:@"word"]) {		
		[[self word]setWordText:[attributeDict objectForKey:@"value"]];
		[[self word]setWordLanguage:[attributeDict objectForKey:@"lang"]];
		[[self word]setWordClass:[attributeDict objectForKey:@"class"]];
		prevElementName = elementName;
	} else if([elementName isEqualToString:@"translation"]) {		
		if ([prevElementName isEqualToString:@"word"])
			[[self word]setWordTranslation:[attributeDict objectForKey:@"value"]];
		else {
			[[self word]appendContent:@": <font color='#660066'>"];
			[[self word]appendContent:[attributeDict objectForKey:@"value"]];
			[[self word]appendContent:@"</font>"];
		}
		prevElementName = elementName;
		
	} else if([elementName isEqualToString:@"phonetic"]) {	

		[[self word]setPhoneticText:[attributeDict objectForKey:@"value"]];
		prevElementName = elementName;

	} else if([elementName isEqualToString:@"synonym"]) {		
		prevElementName = elementName;
	} else if([elementName isEqualToString:@"see"]) {		
		prevElementName = elementName;
	} else if([elementName isEqualToString:@"inflection"]) {
		if ([prevElementName isEqualToString:@"inflection"]){
			
			[[self word]appendContentWithLeadingSpace:[attributeDict objectForKey:@"value"]];
		}
		else {
			[[self word]appendContentWithLeadingNewLine:[attributeDict objectForKey:@"value"]];
		}
		prevElementName = elementName;

		//if ((elementName==nil)||(nil==[attributeDict objectForKey:@"value"])) return;

	} else {	
		[[self word]appendContentWithLeadingNewLine:[attributeDict objectForKey:@"value"]];
		prevElementName = elementName;
	}
	
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
{}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"ERROR:%@", [parseError localizedDescription]);
}


@end
